package com.zlb.leyaoxiu2.sqlite;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.zlb.leyaoxiu2.live.common.utils.GsonUtil;
import com.zlb.leyaoxiu2.live.common.utils.SPUtils;
import com.zlb.leyaoxiu2.live.common.utils.StringUtils;
import com.zlb.leyaoxiu2.live.entity.SearchHistoryMsg;
import com.zlb.leyaoxiu2.live.entity.SearchHotTag;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by plm on 2016/11/9.
 */
public class SearchHistoryUtil {
    public static final String KEY_HISTORY = "search_history";
    public static final int MAXSIZE = 6;


    public static void addSearchTag(Context context, String tag) {
        //String tags = (String) SPUtils.get(context, KEY_HISTORY, null);
        String theLastTags;
        List<SearchHotTag> data = getSearchTag(context);
        if (data != null) {
            if (data.size() >= 0) {
                //检查下里面有没有重复的TAG
                boolean isRepeat = false;
                for (SearchHotTag tempTag : data) {
                    if (tempTag.getHotTagMsg().equals(tag)) {
                        isRepeat = true;
                        //把它移到首位
                        data.remove(tempTag);
                        data.add(0, tempTag);
                        break;
                    }
                }
                if (!isRepeat) {
                    //如果没有重复，删掉最后一个
                    if (data.size() >= MAXSIZE) {
                        data.remove(MAXSIZE - 1);
                    }
                    data.add(0, new SearchHotTag(tag));
                }
            } else {
                if (data == null) {
                    data = new ArrayList<>();
                }
                data.add(0, new SearchHotTag(tag));
            }
            //存起来最新的
            theLastTags = GsonUtil.getInstance().toJson(data);
        } else {
            data = new ArrayList<>();
            data.add(new SearchHotTag(tag));
            theLastTags = GsonUtil.getInstance().toJson(data);
        }
        SPUtils.put(context, KEY_HISTORY, theLastTags);
    }

    public static List<SearchHotTag> getSearchTag(Context context) {
        String tags = (String) SPUtils.get(context, KEY_HISTORY, null);
        if (StringUtils.isNotEmpty(tags)) {
            try {
                List<SearchHotTag> data = GsonUtil.getInstance().fromJson(tags, new TypeToken<List<SearchHotTag>>() {
                }.getType());
                return data;
            } catch (JsonSyntaxException e) {
                return null;
            }
        }
        return null;
    }

    public static void clearSearchTag(Context context) {
        SPUtils.remove(context, KEY_HISTORY);
    }

}
